from rest_framework import permissions

from apps.reviews.models import Review

class IsReviewOwnerOrReadOnly(permissions.BasePermission):
    """
    自定义权限：只允许评价所有者编辑，其他用户只能查看
    """
    def has_object_permission(self, request, view, obj):
        # 允许GET, HEAD, OPTIONS请求
        if request.method in permissions.SAFE_METHODS:
            return True
            
        # 只允许评价的所有者编辑
        return obj.customer == request.user

class IsOrderOwner(permissions.BasePermission):
    """检查用户是否是订单所有者"""
    def has_permission(self, request, view):
        order_id = request.data.get('order')
        return request.user.orders.filter(id=order_id).exists()

class CanReviewOrder(IsOrderOwner):
    """检查订单是否可评价"""
    def has_permission(self, request, view):
        if not super().has_permission(request, view):
            return False
            
        order_id = request.data.get('order')
        return not Review.objects.filter(order_id=order_id).exists()